<?php
/**
 * Created by PhpStorm.
 * User: majiawen
 * Date: 2018/1/31
 * Time: 9:18
 */

namespace app\admin\controller\v1;

use app\admin\service\UserShaohuoService;
use app\admin\controller\Fun;
use app\admin\service\UserVipService;
use app\common\Model\User;
use app\common\Model\UserShaohuo;
use app\common\Model\FuncClass;
use app\common\Model\UserVip;
use think\Db;

/**
 * @title 后台-用户管理-用户管理列表-V1
 * @description 接口说明
 *
 * @header name:copyright require:1 default:v1 desc:版本号(全局)
 */
class UserInfo extends Base
{
    /**
     * @title 用户管理列表
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:userList desc:用户管理列表
     *
     * @param name:page type:string require:1 default: other: desc:页码
     * @param name:page_size type:string require:1 default: other: desc:每页个数
     * @param name:search type:string require:1 default: other: desc:查询数据
     * @param name:sort_field type:string require:1 default: other: desc:排序字段
     * @param name:sort_type type:string require:1 default: other: desc:0正序,1倒序
     * @param name:type type:string require:1 default: other: desc:捎货用户类型:普通用户-1捎货用户类型>0
     * @param name:vip type:string require:1 default: other: desc:普通用户-1vip用户类型1
     * @param name:status type:string require:1 default: other: desc:用户状态:1为有效,0为禁用
     * @param name:is_withdraw type:string require:1 default: other: desc:能否提现:0为允许,1为不允许
     * @param name:start_time type:string require:1 default: other: desc:用户注册开始查询时间
     * @param name:end_time type:string require:1 default: other: desc:用户注册结束查询时间
     *
     * @return data:['list'=>[],'totalPage'=>2 ]
     * 根据 页码 搜索 权限 查询用户列表
     */
    public function userList()
    {
        $where = [];
        //查询
        if (isset($this->param['search']) && $this->param['search'] != '') {
            $search = $this->param['search'];
            $where['mobile|real_name|nick_name'] = ['like', '%' . $search . '%'];
        }
        $used_sort_field = [
            'uid', 'mobile', 'salt', 'status', 'sex', 'real_name', 'nick_name', 'birthday', 'header_img', 'signature',
            'access_token', 'token_expired', 'region_id', 'balance', 'is_withdraw', 'withdraw_reason', 'withdraw_pwd',
            'unionid', 'create_time', 'update_time', 'ub_id', 'recharge_balance', 'withdraw_balance', 'frozen_balance',
            'shaohuo_status', 'shaohuo_type', 'vip_status', 'start_time', 'end_time'
        ];
        if (isset($this->param['sort_field']) && $this->param['sort_field'] != '' && in_array($this->param['sort_field'], $used_sort_field) && isset($this->param['sort_type'])) {
            if ($this->param['sort_field'] == 'uid') {
                $this->param['sort_field'] = 'u.uid';
            }
            $order = [
                $this->param['sort_field'] => $this->sort_type[intval($this->param['sort_type'])]
            ];
        } else {
            $order = ['u.uid' => $this->sort_type[1]];
        }
        //普通用户-1  捎货用户类型>0
        $where2 = '1=1';
        if (isset($this->param['type']) && $this->param['type'] != '') {
            $type = intval($this->param['type']);
            if ($type == -1) {
                $where2 = '(s.status is NULL OR s.status = 0)';
            } elseif ($type > 0) {
                //查询捎货人种类是否存在
                $where = ['fc_id' => $type];
                if (FuncClass::getAllFunc($where, 'fc_id')) {
                    $where2 = 's.status = ' . UserShaohuo::STATUS_NORMAL . ' AND s.fc_id = ' . $type;
                }
            }
        }
        //普通用户-1  vip用户类型1
        $where3 = '1=1';
        if (isset($this->param['vip']) && $this->param['vip'] != '') {
            $type = intval($this->param['vip']);
            $time = date('Y-m-d H:i:s');
            if ($type == -1) {
                $where3 = 'v.status is NULL OR v.status = 0 OR v.start_time > "' . $time . '" OR v.end_time < "' . $time . '"';
            } elseif ($type == 1) {
                $where3 = 'v.status = ' . UserVip::STATUS_NORMAL . ' AND v.start_time < "' . $time . '" AND v.end_time > "' . $time . '"';
            }
        }
        //用户状态:1为有效,0为禁用
        if (isset($this->param['status']) && $this->param['status'] != '') {
            $status = intval($this->param['status']) == 1 ? 1 : 0;
            $where['u.status'] = $status;
        }
        //能否提现:0为允许,1为不允许
        if (isset($this->param['is_withdraw']) && $this->param['is_withdraw'] != '') {
            $is_withdraw = $this->param['is_withdraw'] == 1 ? 1 : 0;
            $where['is_withdraw'] = $is_withdraw;
        }
        $where4 = '1=1';
        //用户注册时间
        if (isset($this->param['start_time']) && $this->param['start_time'] != '') {
            $start_time = $this->param['start_time'];
            $where4 = "u.create_time >= '$start_time'";
        }
        if (isset($this->param['end_time']) && $this->param['end_time'] != '') {
            $end_time = $this->param['end_time'];
            if (strlen($where4) > 5) {
                $where4 .= "AND u.create_time <= '$end_time'";
            } else {
                $where4 = "u.create_time <= '$end_time'";
            }
        }
        $list = Db::name('user u')
            ->join('user_balance b', 'b.uid=u.uid', 'left')
            ->join('user_shaohuo s', 's.uid=u.uid', 'left')
            ->join('user_vip v', 'v.uid=u.uid', 'left')
            // ->join('user_shaohuo_funcs t', 't.uid=s.uid', 'left')
            // ->join('func_class f', 'f.fc_id=t.fc_id', 'left')
            ->where($where)
            ->where($where2)
            ->where($where3)
            ->where($where4)
            ->order($order)
            ->field('
            u.uid ,
            u.mobile ,
            u.status ,
            u.nick_name ,
            u.is_withdraw ,
            u.create_time ,
            b.recharge_balance ,
            b.withdraw_balance ,
            u.type vip_type ,
            b.frozen_balance ,
            s.status shaohuo_status ,
            v.status vip_status ,
            v.start_time vip_start_time,
            v.end_time vip_end_time
            ')
            ->paginate($this->page_size, false, ['page' => $this->param['page']]);
        if ($list) {
            $User = new User();
            $UserVip = new UserVip();
            $data = [];
            foreach ($list->items() as $k => $v) {
                $arr = [
                    'uid' => $v['uid'],
                    'mobile' => $v['mobile'],
                    'status' => $User->_status[$v['status']],
                    'nick_name' => $v['nick_name'],
                    'is_withdraw' => $v['is_withdraw'],
                    'create_time' => $v['create_time'],
                    'balance' => $v['recharge_balance'] + $v['withdraw_balance'],
                    'frozen_balance' => empty($v['frozen_balance']) ? 0 : $v['frozen_balance'],
                ];
                //捎货人状态:1有效,0禁用
                // if (empty($v['shaohuo_status'])) {
                //     $arr['shaohuo_name'] = '普通用户';
                // } else {
                //     $arr['shaohuo_name'] = $v['shaohuo_name'];
                // }
                //用户类型:0:普通用户,1:会员
                //VIP状态:0禁用,1有效
                if ($v['vip_type'] == $User::TYPE_VIP && $v['vip_status'] == $UserVip::STATUS_NORMAL) {
                    $arr['vip'] = $User->_type[$v['vip_type']];
                    $arr['vip_start_time'] = empty($v['vip_start_time']) ? 0 : $v['vip_start_time'];
                    $arr['vip_end_time'] = empty($v['vip_end_time']) ? 0 : $v['vip_end_time'];
                } else {
                    $arr['vip'] = $User->_type[$User::TYPE_NORMAL];
                    $arr['vip_start_time'] = 0;
                    $arr['vip_end_time'] = 0;
                }

                $data[] = $arr;
            }
            return Fun::success([
                'list' => $data,
                'total_num' => $list->total()
            ]);
        } else {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }

    /**
     * @title 修改用户状态
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default:alertUserStatus other:alertUserStatus desc:修改用户状态
     *
     * @param name:uids type:string require:1 default: other:10086,10087,10088 desc:用户id
     * @param name:status type:string require:1 default: other:0 desc:用户状态:1为有效,0为禁用,''不改变
     * @param name:is_withdraw type:string require:1 default: other:0 desc:能否提现:0为允许,1为不允许,''不改变
     *
     * @return data:[]
     */
    public function alertUserStatus()
    {
        $uids = explode(',', trim($this->param['uids'], ','));
        $updata = [];

        //用户状态:1为有效,0为禁用
        if (isset($this->param['status']) && $this->param['status'] != '') {
            $updata['status'] = $this->param['status'] == 1 ? 1 : 0;
        }

        //能否提现:0为允许,1为不允许
        if (isset($this->param['is_withdraw']) && $this->param['is_withdraw'] != '') {
            $updata['is_withdraw'] = $this->param['is_withdraw'] == 1 ? 1 : 0;
        }
        if (count($updata) && count($uids)) {
            $user = New User();
            $res = $user->where('uid', 'in', $uids)
                ->update($updata);
            if ($res) {
                return Fun::success('');
            } else {
                return Fun::error('');//TODO 无数据，定义错误类型
            }
        }
        return Fun::error('');//TODO 无数据，定义错误类型
    }

    /**
     * @title 创建用户
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default:createUser other:createUser desc:创建用户
     *
     * @param name:mobile type:string require:1 default: other:18346179409 desc:用户手机号
     *
     * @return data:[]
     */
    public function createUser()
    {
        $mobile = $this->param['mobile'];

        $user = New User();
        $update = ['mobile' => $mobile];
        $res = $user->where($update)->field('uid')->find();
        if ($res) {
            return Fun::error('101000');//帐号已经存在
        }
        $res = $user->data(['mobile' => $mobile])->save();
        if ($res) {
            return Fun::success('');
        }
        return Fun::error('');//TODO 无数据，定义错误类型
    }

    /**
     * @title 修改用户类型(比如成为捎货人或者VIP)
     * @description
     * @author majiawen
     * @url /admin/index/index
     * @method POST
     *
     * @header name:interface require:1 default:UserInfo desc:接口组(全局)
     * @header name:access_token type:string require:1 default: other: desc:身份验证参数,登陆时返回
     *
     * @param name:acc_id type:string require:1 default: other: desc:身份验证参数,登陆时返回
     * @param name:command type:string require:1 default: other:alertUserType desc:修改用户状态
     *
     * @param name:uids type:string require:1 default: other:10086,10087,10088 desc:用户id
     * @param name:shaohuo type:string require:1 default: other:0 desc:成为捎货人:-1为变成普通用户,0为不改变,>1为变成先相应的捎货人
     * @param name:vip type:string require:1 default: other:0 desc:能否提现:-1为变成非会员,0为不改变,1为成为会员
     *
     * @return data:[]
     */
    public function alertUserType()
    {
        if (empty($this->param['uids'])) {
            return Fun::error('');//TODO 无数据，定义错误类型
        }
        $uids = explode(',', trim($this->param['uids'], ','));

        $shaohuo = intval($this->param['shaohuo'] ?? 0);
        $vip = intval($this->param['vip'] ?? 0);
        $start_time = empty($this->param['start_time']) ? '' : $this->param['start_time'];
        $end_time = empty($this->param['end_time']) ? '' : $this->param['end_time'];

        // 启动事务
        Db::startTrans();
        try {


            //成为捎货人:-1为变成普通用户,0为不改变,>1为变成先相应的捎货人
            if ($shaohuo == -1) {
                $UserShaohuo = New UserShaohuo;
                $UserShaohuo->where('uid', 'in', $uids)->update(['status' => UserShaohuo::STATUS_FORBID]);
            } elseif ($shaohuo > 0) {
                //查询捎货人种类是否存在
                $where = ['fc_id' => $shaohuo];
                if (FuncClass::getAllFunc($where, 'fc_id')) {
                    UserShaohuoService::alterShaohuoTypeByUids($uids, $shaohuo);
                }
            }
            //能否提现:-1为变成非会员,0为不改变,1为成为会员
            if ($vip == -1) {
                $UserVip = New UserVip();
                $UserVip->where('uid', 'in', $uids)->update(['status' => UserVip::STATUS_FORBID]);
            } elseif ($vip == 1) {
                UserVipService::alterVipTypeByUids($uids, $start_time, $end_time);
            }


            // 提交事务
            Db::commit();
            return Fun::success('');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return Fun::error('');//TODO 无数据，定义错误类型
        }
    }
}